import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs';
import {UserService} from '../api/user.service';
import * as _ from 'underscore';


@Injectable({
  providedIn: 'root'
})
export class UserGuardService implements CanActivate {

  constructor(private user: UserService, private router: Router) {
  }

  check(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return new Observable<boolean>((observe) => {
      this.user.menuObserver().subscribe((menus) => {
        let first_leaf_node = null;
        let ret = false;
        menus.list.forEach((item) => {
          if (item.link === state.url) {
            ret = true;
          }
          if (!first_leaf_node && item.sub_menu.length === 0) {
            first_leaf_node = item;
          }
        });

        this.user.userObserver().subscribe((user) => {
          ret = route.data.apiNames.every((value) => {
            return Boolean(_.find(user.permission_group.api, (v: any) => v.name === value));
          });
          if (!ret) {
            this.router.navigate([first_leaf_node.link]).catch();
          }
          observe.next(ret);
          observe.complete();
        });
      });
    });
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.check(route, state);
  }
}
